/**
 * @version     1.0.0
 * @package     mylits engine
 * @license     GNU General Public License version 3
 * @author      Arfan Fudyartanto D N <arfan@mylits.com> - http://engine.mylits.com
 */
var hideLoader = false;
jQuery(document).ready(function() {
    /**
     * loader bar begin
     */
    jQuery(document).ajaxStart(function() {
        if (!hideLoader) {
            jQuery("#ajax-loader").fadeIn();
        }
    });
    jQuery(document).ajaxStop(function() {
        jQuery("#ajax-loader").fadeOut();
    });
    /**
     * loader bar end
     */


    /**
     * popup begin
     */
    jQuery('body').delegate('a.popup', 'click', function() {
        var target = jQuery(this).attr('href');
        var popup = jQuery('');
        jQuery.get(target, function(data) {
            data = cleanScripts(data);
            jQuery('body').append('<div class="popup-container"><div class="popup-toolbar gray"><a href="javascript:void(0)" class="glyphicon glyphicon-remove popup-close"></a></div><div class="popup-content">' + data + '</div></div>');
            jQuery('.popup-container').fadeIn();
        });
        return false;
    });
    jQuery('body').delegate('.popup-close', 'click', function() {
        var popup = jQuery(this).parents(':eq(1)');
        popup.fadeOut();
        setTimeout(function() {
            popup.detach();
        }, 500);
    });
    /**
     * popup end
     */


    /**
     * ajax form begin
     */
    jQuery('body').delegate('.form', 'submit', function() {
        if (jQuery(this).hasClass('ajax')) {
            var action = jQuery(this).attr('action');
            var method = jQuery(this).attr('method');
            var target = jQuery(this).attr('class').split('target-')[1];

            if (method == 'post') {
                jQuery.post(action, jQuery(this).serialize(), function(data) {
                    data = cleanScripts(data);
                    jQuery('.' + target).html(data);
                });
            }
            return false;
        }
    });
    /**
     * ajax form end
     */

    /**
     * confirm begin
     */
    jQuery('body').delegate('.confirm', 'click', function() {
        hideLoader = true;
        jQuery('.confirm-container').detach();
        var offset = jQuery(this).offset();
        var left = offset.left;
        var top = offset.top;
        var confirm = jQuery('<div class="confirm-container"></div>');

        confirm.css({
            'top': top + 'px',
            'left': left + 'px'
        });

        var yesClass = '';
        if (jQuery(this).hasClass('ajax')) {
            yesClass = ' link-ajax target-' + jQuery(this).attr('class').split('target-')[1];
        }

        confirm.html('<div class="gray">' + Mylits_Language('confirm') + '</div><div class="confirm-body">' + Mylits_Language('are_you_sure') + '</div><div class="gray"><a class="btn confirm-close' + yesClass + '" href="' + jQuery(this).attr('href') + '">' + Mylits_Language('yes') + '</a> <button class="btn confirm-close">' + Mylits_Language('cancel') + '</button></div></div>');

        jQuery('body').append(confirm);
        hideLoader = false;
        return false;
    });

    jQuery('body').delegate('.confirm-close', 'click', function() {
        jQuery('.confirm-container').detach();
    });
    /**
     * confirm end
     */

    /**
     * ajax link
     */
    jQuery('body').delegate('.link-ajax', 'click', function() {
        var target = jQuery(this).attr('class').split('target-')[1];
        var location = target + '*' + jQuery(this).attr('href').replace(BASE_URL, '');
        var current = window.location;
        if (current.toString().split('#!').length > 1) {
            current = current.toString().split('#!')[0];
        }
        window.location = current + '#!' + location;
        return false;
    });
    /**
     * ajax link end
     */

    var location = window.location;
    if (location.toString().split('#!').length > 1) {
        executeHash(location.toString());
    }

    jQuery(window).hashchange(function() {
        var hash = location.hash;
        executeHash(hash);
    });
});

function executeHash(url) {
    if (url.split('#!').length > 1) {
        var str = url.split('#!')[1].toLowerCase();
        if (str.split('*').length > 1) {
            var target = str.split('*')[0];
            var href = str.split('*')[1];
            if (href.split('http').length <= 1) {
                href = BASE_URL + href;
            }
            setContent(jQuery('.' + target), href);
        }
    } else {
        window.location = window.location;
    }
}


/**
 * Function to replace content with ur content
 * 
 * @param jQueryObject target
 * @param string url
 */
function setContent(target, url) {
    jQuery.get(url, function(data) {
        data = cleanScripts(data);
        target.html(data);
    });
}

/**
 * Function to close all open mylits popup
 */
function popupClose() {
    jQuery('.popup-container').fadeOut();
    setTimeout(function() {
        jQuery('.popup-container').detach();
    }, 500);
}


/**
 * Function to get languge translation
 * 
 * @param string keyLang
 * @returns string value
 */
function Mylits_Language(keyLang) {
    jQuery.ajaxSetup({async: false});
    var response;
    jQuery.post(BASE_URL + 'core.services', {"method": "Mylits_Language", "params": [keyLang]}, function(data) {
        response = jQuery.parseJSON(data);
    });
    jQuery.ajaxSetup({async: true});
    return response.result;
}

/**
 * prevent script loaded twice
 */
function cleanScripts(data) {
    var readyScript = new Array();
    jQuery('script').each(function() {
        if (jQuery.type(jQuery(this).attr('src')) !== 'undefined') {
            readyScript.push(jQuery(this).attr('src'));
        }
    });
    var obj = jQuery('<div></div>');
    obj.html(data);
    var scripts = obj.find('script');
    scripts.each(function() {
        if (jQuery.type(jQuery(this).attr('src')) !== 'undefined') {
            if (readyScript.indexOf(jQuery(this).attr('src')) >= 0) {
                jQuery(this).detach();
            }
        }
    });
    return  obj.html();
}

var key = "SXGWLZPDOKFIVUHJYTQBNMACERxswgzldpkoifuvjhtybqmncare";
function encodeStr(uncoded) {
    uncoded = uncoded.toUpperCase().replace(/^\s+|\s+$/g, "");
    var coded = "";
    var chr;
    for (var i = uncoded.length - 1; i >= 0; i--) {
        chr = uncoded.charCodeAt(i);
        coded += (chr >= 65 && chr <= 90) ?
                key.charAt(chr - 65 + 26 * Math.floor(Math.random() * 2)) :
                String.fromCharCode(chr);
    }
    return encodeURIComponent(coded);
}

function decodeStr(coded) {
    coded = decodeURIComponent(coded);
    var uncoded = "";
    var chr;
    for (var i = coded.length - 1; i >= 0; i--) {
        chr = coded.charAt(i);
        uncoded += (chr >= "a" && chr <= "z" || chr >= "A" && chr <= "Z") ?
                String.fromCharCode(65 + key.indexOf(chr) % 26) :
                chr;
    }
    return uncoded;
}